package source;

import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;

/**
 * 自定义带有并行度的Source
 */
public class CustomSource3 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        DataStreamSource<String> data = env.addSource(new CustomParSource());
        data.print();

        env.execute("CustomSource3");
    }

    static class CustomParSource extends RichParallelSourceFunction<String> {

        private static boolean flag = true;

        @Override
        public void open(Configuration parameters) throws Exception {
            // 获取连接
        }

        // 产生数据的方法
        @Override
        public void run(SourceContext<String> ctx) throws Exception {
            int i = 1;
            // 获取当前执行的task的上下文
            RuntimeContext runtimeContext = getRuntimeContext();
            int index = runtimeContext.getIndexOfThisSubtask();
            while (flag){
                ctx.collect("subtask index: " + index + ", " + i++);
            }
        }

        @Override
        public void cancel() {
            flag = false;
        }

        @Override
        public void close() throws Exception {
            // 关闭连接
        }
    }
}
